<?php
/**
 * <pre>
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT      : rubik-base
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * [GENERAL INFO OF THIS FILE] 
 *
 * </pre>
 * 
 * @version 		1.0
 * @author			Dang Nhon Hoa <hoadn@rubik.com.vn>
 * @access			public
 * @package			rubik.base.html
 *
 * Created on	: May 25, 2008
 */
RCoreImporter::cls("helper.RFileFolderHelper" );
RCoreImporter::cls( "html.HtmlControl" );

class BasicHtmlUploadControl extends HtmlControl {
	
	/**
	 * All supported type for this UploadForm
	 * Ex: ".mp3, .swf, .wma"
	 * 
	 * @var string
	 */
	var $_supportedTypes = null;
	
	/**
	 * Path from root. The path to place file from the root
	 *
	 * @var string
	 */
	var $_pathFromRoot = null;
	
	/**
	 * Error Message
	 *
	 * @var string
	 */
	var $_errorMsg = null;
	
	/**
	 * If the value has updated (not get from the old one, then the flag is true
	 * @var boolean
	 */
	var $_hasUpdate = false;

	/**
	 * The file size that system limited for this component
	 * @var number
	 */
	var $_fileSizeLimit = null;
	
	/**
	 * Support URL direct input or not
	 *
	 * @var string
	 */
	var $_supportURL = false;
	
	/**
	 * Construtor
	 *
	 * @param string $inputName
	 * @param string $pathFromRoot Ex: "uploadFiles/images/"
	 * @param string/array $valueOrArrayContain if array normaly it should be: $_GET, $_POST, $_REQUEST
	 * @param string $supportedTypes Ex: ".mp3, .swf, .wma" 
	 * @param boolean $supportURL
	 * @return BasicHtmlUploadControl
	 */
	function __construct($inputName, $pathFromRoot=null, $valueOrArrayContain = null, $supportedTypes = null, $supportURL = false) {
		$this->_inputName = $inputName;
		$this->_supportedTypes = $supportedTypes;
		$this->_pathFromRoot = $pathFromRoot;
		$this->setValue ( $valueOrArrayContain );
		$this->_supportURL = $supportURL;
	}
	
	/**
	 * Set value for this
	 *
	 * @param string/array $valueOrArrayContain
	 */
	function setValue($valueOrArrayContain) {
		if (!$valueOrArrayContain) {
			return false;
		}
		if (! is_array ( $valueOrArrayContain )) {
			if (is_object($valueOrArrayContain)) {
				$this->_value = RubikHelper::getValueFrom($valueOrArrayContain, $this->_inputName);
			}
			else {
				$this->_value = $valueOrArrayContain;
			}
			return;
		}
		
		$inputName = $this->_inputName;
		$oldName = "old_upload_{$inputName}";
		$checkName = $inputName . '_type';
		
		if ($valueOrArrayContain[$inputName.'_dual']) {
			$oldLink = ($valueOrArrayContain [$oldName]);
			if ($valueOrArrayContain[$checkName] == 'text') {
				$this->_value = $oldLink;
				return $oldLink;
			}
		}
		else {
			$oldLink = @base64_decode($valueOrArrayContain [$oldName]);
		}
		if ($_FILES [$inputName]['error']) {
			$this->setError($_FILES [$inputName]['error']);
			$this->_value = $oldLink;
			return $oldLink;
		}
		
		if (! empty ( $oldLink ) && strpos ( $oldLink, "://" ) === false) {
			@unlink ( $this->getAbsRootPath () . $oldLink );
		}

		$file_name = $_FILES [$inputName] ['name'];
		$temp_file = $_FILES [$inputName] ['tmp_name'];
		if ($this->_fileSizeLimit) {
			if ($_FILES [$inputName] ['size'] > $this->_fileSizeLimit) {
				$this->setError('The uploaded file has over the limit file size.');
				return $sUploadValue;
			}
		}
		$temp_file = $_FILES [$inputName] ['tmp_name'];
		$folder = $this->getAbsRootPath () . $this->_pathFromRoot;
		$sUploadValue = RFileFolderHelper::uploadFile ( $temp_file, $file_name, $folder, $this->_supportedTypes );
		
		if ($sUploadValue === false) {
			$this->setError ( 'Upload picture error!' );
		} else {
			$sUploadValue = $folder . $sUploadValue;
		}
		
		$this->_value = $sUploadValue;
		$this->_hasUpdate = true;
		return $sUploadValue;
	}
	
	/**
	 * Check if the content has update from the original or not!
	 * @return boolean
	 */
	function hasUpdate() {
		return $this->_hasUpdate;
	}
	
	/**
	 * Create the HTML text for doing upload
	 *
	 * @param int $inputSize view size of html
	 * @param string $cssCls
	 * @return string: html string
	 */
	function createUploadFormHtml($attribute = '', $showAcceptMsg = true, $idInput = null) {
		static $idStatic;
		if ($idInput) {
			$id = $idInput;
		}
		else {
			$id = &$idStatic;
		}
		$supportFileTypes = $this->_supportedTypes;
		$acceptMsg = SysLanguage::_ ( "Only accept file type" ) . ": {$supportFileTypes}";
		
		if (empty ( $id )) {
			$id = 1;
			$acceptJs = SysLanguage::_ ( "Only accept file type" ) . ": ";
			// print the check javascript for the first time
			$script = '
			function checkValidFileTypeForUpload(ele , acceptFileType) {
				if (acceptFileType == \'\' || acceptFileType == undefined) {
					return true;
				} 
				testString = ele.value;
				testString = testString.toLowerCase();
				
				arrType = acceptFileType.toLowerCase().split(",");
				
				size = arrType.length;
				for (i = 0; i < size; i++) {
					ext = trim(arrType[i]);
					ext = ext.replace("*.", ".");
					if (ext != "" && testString.lastIndexOf(ext) != -1){
						return true;
					}
				}
			
				alert("' . $acceptJs . '" + acceptFileType);
				emptyValue(ele);
				ele.focus();
				return false;
			}';
			SysResponse::addJavascriptContent ( $script );
		}
		
		$inputName = $this->_inputName;
		$value = $this->_value;
		
		if ($supportFileTypes && $showAcceptMsg) {
			$strCommentTypeUpload = "<em>($acceptMsg) </em>";
		}
		$inputId = $inputName . $id;
		
		
		if ($this->_supportURL) {
			$script = '
			function tongleUploadTypeForm (icheck) {
				var eleId = icheck.id;
				var inputId = eleId.substring(0, eleId.length - 5);
				
				var iurl = document.getElementById("old_upload_" + inputId );
				var ifile = document.getElementById(inputId);

				if (icheck.checked == true) {
					iurl.style.display = \'inline\';
					// clean the file
					emptyValue(ifile);
					ifile = document.getElementById(inputId);
					ifile.style.display = \'none\';
				} else {
					iurl.style.display = \'none\';
					ifile.style.display = \'inline\';
				}
			}
			';
			SysResponse::addJavascriptContent ( $script );
			$sout = '<input type="checkbox" onclick="tongleUploadTypeForm(this);" style="width: 20px;" id="'.$inputId.'_type" name="' . $inputName . '_type" value="text" />';
			$sout .= '<input type="hidden" name="' . $inputName . '_dual" value="1" />';
			$sout .= '<input type="texbox" onfocus="this.select();" style="display:none;" onchange="checkValidFileTypeForUpload(this, \'' . $supportFileTypes . '\');" id="old_upload_'.$inputId.'" name="old_upload_' . $inputName . '" value="' . ( $value ) . '"/>';
			$attribute .= ' onchange="checkValidFileTypeForUpload(this, \'' . $supportFileTypes . '\');" ';
			$sout .= $this->createInputHtml ( "file", $attribute, $inputId );
			$sout .= $strCommentTypeUpload;
			$id ++;
			return $sout;
		}
		
		$attribute .= ' onchange="checkValidFileTypeForUpload(this, \'' . $supportFileTypes . '\');" ';
		$sout .= $this->createInputHtml ( "file", $attribute, $inputId );
		$sout .= '<input type="hidden" name="old_upload_' . $inputName . '" value="' . base64_encode ( $value ) . '"/>';
		$sout .= $strCommentTypeUpload;
		$id ++;
		return $sout;
	}
	
	/**
	 * Get the originally value of this.
	 *
	 * @return string
	 */
	function getOriginallyValue() {
		return $this->_value;
	}
	
	/**
	 * Get the value without link to current site
	 *
	 * @return string
	 */
	function getValueWithoutUrl() {
		$value = $this->_value;
		$value = str_replace ( $this->getRootUrlPath (), "", $value );
		$value = str_replace ( $this->getAbsRootPath (), "", $value );
		return $value;
	}
	
	/**
	 * Get the root URL
	 * Ex: "http://rubik.com.vn/application"
	 * 
	 * @abstract this function must be overide by subClass
	 *
	 * @return string the http:// path of current site
	 */
	function getRootUrlPath() {
		return SYS_ROOT_URL;
	}
	
	/**
	 * Get the absolute path of root folder
	 * Ex: "D:\www\rubik\application"
	 * @abstract this function must be overide by subClass
	 *
	 * @return string the  path of current site
	 */
	function getAbsRootPath() {
		return SYS_ROOT_PATH;
	}

}
?>
